package com.sunxd.zstudy.juc.T19_container.specialQueue;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延迟队列
 * @author: 作者名称
 * @date: 2021-09-13 14:25
 **/
public class T1DelayQueue {

    public static void main(String[] args) throws InterruptedException {
        DelayQueue<MyTask> delayQueue = new DelayQueue<>();
        long current = System.currentTimeMillis();
        MyTask k1 = new MyTask("t1",current+ 3000);
        MyTask k2 = new MyTask("t2",current+ 1000);
//        MyTask k3 = new MyTask("t3",current+ 7000);
//        MyTask k4 = new MyTask("t4",current+ 5000);
        delayQueue.add(k1);
        delayQueue.add(k2);
//        delayQueue.add(k3);
//        delayQueue.add(k4);
        System.out.println(delayQueue);
        while (true){
            MyTask myTask = delayQueue.take();
            if (myTask == null) {
                break;
            }
            System.out.println(myTask.getName());
        }

    }

    static class MyTask implements Delayed {

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public long getRunningTime() {
            return runningTime;
        }

        public void setRunningTime(long runningTime) {
            this.runningTime = runningTime;
        }

        String name;
        long runningTime;

        public MyTask(String name, long rt) {
            this.name = name;
            this.runningTime = rt;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(runningTime - System.currentTimeMillis(), TimeUnit.MICROSECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            System.out.println("self"+this.getDelay(TimeUnit.MICROSECONDS));
            System.out.println("other"+o.getDelay(TimeUnit.MICROSECONDS));
            if (this.getDelay(TimeUnit.MICROSECONDS) == o.getDelay(TimeUnit.MICROSECONDS)) {
                return 0;
            } else {
                return this.getDelay(TimeUnit.MICROSECONDS) > o.getDelay(TimeUnit.MICROSECONDS) ? 1 : -1;
            }
        }
    }
}
